﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PhotoGallery.Infrastructure;
using PhotoGallery.Core.Business;
using System.IO;

namespace PhotoGallery
{
    /// <summary>
    /// Summary description for Image
    /// </summary>
    public class Image : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/octet-stream";
            context.Response.BinaryWrite(HanlderData(context));
        }

        private byte[] HanlderData(HttpContext context)
        {
            StreamReader reader = null;
            byte[] buffer = null;
            Stream stream = null;

            string fileName = string.Empty;
            string type = string.Empty;

            if (CY.Utility.Common.RequestUtility.IsGet)
            {
                fileName = CY.Utility.Common.RequestUtility.GetQueryString("name");
                type = CY.Utility.Common.RequestUtility.GetQueryString("type");
            }
            else if (CY.Utility.Common.RequestUtility.IsPost)
            {
                fileName = CY.Utility.Common.RequestUtility.GetFormString("name");
                type = CY.Utility.Common.RequestUtility.GetQueryString("type");
            }

            if (string.IsNullOrEmpty(type))
                type = "small";

            string imgName = CY.Utility.Common.FileUtility.GetFileName(fileName);
            string imgExtention = CY.Utility.Common.FileUtility.GetFileExtension(fileName);

            // 临时文件夹目录
            DirectoryInfo dir = new DirectoryInfo(FileConfiguration.TmpRoots.FullName + "\\");

            if (System.IO.File.Exists(dir + imgName + "_" + type + imgExtention))
            {
                reader = new StreamReader(dir.FullName + fileName + type + imgExtention);
            }
            else
            {
                reader = new StreamReader(FileConfiguration.DefaultImgPath);
            }
            if (reader != null)
            {
                buffer = new byte[reader.BaseStream.Length];
                reader.BaseStream.Read(buffer, 0, Convert.ToInt32(reader.BaseStream.Length));
                reader.Close();
            }

            if (buffer == null)
            {
                buffer = new byte[1];
            }

            return buffer;

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}